package com.aisile.base.service;

import com.aisile.base.dao.LabelDao;
import com.aisile.base.pojo.Label;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import util.IdWorker;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @标题 LabelService
 * @作者 Mr.chen
 * @创建日期 2019/4/17 21:32
 * @版本号 1.0
 **/
@Service
public class LabelService {
    @Autowired
    private LabelDao labelDao;
    @Autowired
    IdWorker idWorker;

    /**
     * 查询全部
     * @return
     */
    public List<Label> findAll(){
        return labelDao.findAll();
    }

    /**
     * 根据ID 进行查询
     * @param id
     * @return
     */
    public Label findById(String id){
        return labelDao.findById(id).get();
    }

    /**
     * 添加标签
     * @param label
     */
    public void add(Label label){
        label.setId(idWorker.nextId()+"");
        labelDao.save(label);
    }

    /**
     * 修改标签
     * @param label
     */
    public void update(Label label){
        labelDao.save(label);
    }

    /**
     * 根据ID删除
     * @param id
     */
    public void deleteById(String id){
        labelDao.deleteById(id);
    }

    /**
     * 规格模糊查询
     * @param searchMap
     * @return
     */
    public List<Label> findSearch(Map searchMap){
        return labelDao.findAll(createSpecification(searchMap));
    }
    public Page<Label> findSearch(Map searchMap, int page, int size){
        PageRequest pageRequest = PageRequest.of(page,size);
        return labelDao.findAll(createSpecification(searchMap),pageRequest);
    }

    /**
     * 创建条件
     * @param searchMap
     * @return
     */
    public Specification<Label> createSpecification(Map searchMap){
        return (root,cq,cb) -> {
            List<Predicate> list = new ArrayList<>();
            String labelname = (String)searchMap.get("labelname");
            String state = (String)searchMap.get("state");
            String recommend = (String)searchMap.get("recommend");
            if(!StringUtils.isEmpty(labelname)){
                list.add(cb.like(root.get("labelname"), "%" + labelname + "%"));
            }
            if(!StringUtils.isEmpty(state)){
                list.add(cb.equal(root.get("state"), state));
            }
            if(!StringUtils.isEmpty(recommend)){
                list.add(cb.equal(root.get("recommend"), recommend));
            }
            return cb.and(list.toArray(new Predicate[list.size()]));
        };
    }
}
